<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/6/6
 * Time: 11:16
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Common\Business;

use App\Common\Lib\Log\Log;
use App\Exception\FooException;
use App\Model\UserBrowsingHistory;

class UserBrowsingHistoryBusiness extends BusBase
{
    protected $obj_model;

    public function __construct()
    {
        $this->obj_model = new UserBrowsingHistory();
    }

    /**
     * @param int $goods_id
     * @param int $user_id
     * @return int
     */
    public function getUserHistoryInfo(int $goods_id = 0, int $user_id = 0): int
    {
        $where = [
            ['goods_id', '=', $goods_id],
            ['user_id', '=', $user_id]
        ];
        try {
            $row = $this->obj_model->where($where)
                ->first();
            if (!$row) {
                $insert_data = [
                    'goods_id' => $goods_id,
                    'user_id' => $user_id,
                    'number' => 1,
                    'create_time' => time()
                ];
                $result = $this->obj_model->insert($insert_data);
            } else {
                $result = $this->obj_model->where($where)->update([
                    'number' => $row['number'] + 1,
                    'update_time' => time()
                ]);
            }
        } catch (\Exception $e) {
            Log::get('browsing_user', 'error')->error($e->getMessage());
            throw new FooException("查询失败");
        }
        if (!$result) {
            throw new FooException("操作失败");
        }
        try {
            $count = $this->obj_model->where('goods_id', $goods_id)
                ->count();
        } catch (\Exception $e) {
            Log::get('browsing_user', 'error')->error($e->getMessage());
            throw new FooException("查询失败");
        }
        return $count;
    }
}